<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' data: https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' data: https://cdn.jsdelivr.net; font-src 'self' https://cdn.jsdelivr.net; connect-src 'self'; img-src 'self' data: https:;">
    <title>统计分析 - 百日行动线索收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="css/admin-mobile.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            z-index: 1000;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 10px;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
            margin-bottom: 20px;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: white;
        }
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .filter-card {
            background: white;
            border-radius: 15px;
            padding: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .data-table {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .trend-item {
            padding: 10px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .trend-item:last-child {
            border-bottom: none;
        }
        .trend-value {
            font-size: 1.2rem;
            font-weight: bold;
        }
        .trend-change {
            font-size: 0.9rem;
        }
        .trend-up {
            color: #28a745;
        }
        .trend-down {
            color: #dc3545;
        }
        .trend-stable {
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- 移动端头部 -->
    <div class="mobile-header">
        <button class="mobile-menu-btn" id="mobileMenuBtn">
            <i class="bi bi-list"></i>
        </button>
        <h5 class="mb-0">统计分析</h5>
        <div class="dropdown">
            <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="bi bi-person-circle"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item" href="#" id="mobileLogoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
            </ul>
        </div>
    </div>
    
    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-overlay"></div>
    
    <!-- 侧边栏 -->
    <nav class="sidebar" id="sidebar">
        <div class="p-3">
            <h5 class="text-white mb-4">
                <i class="bi bi-shield-check me-2"></i>
                管理后台
            </h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="/admin/dashboard.html">
                        <i class="bi bi-speedometer2 me-2"></i>仪表板
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/clues.html">
                        <i class="bi bi-file-text me-2"></i>线索管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/admin/statistics.html">
                        <i class="bi bi-bar-chart me-2"></i>统计分析
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/users.html">
                        <i class="bi bi-people me-2"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/settings.html">
                        <i class="bi bi-gear me-2"></i>系统设置
                    </a>
                </li>
            </ul>
        </div>
        <div class="mt-auto p-3">
            <button class="btn btn-outline-light btn-sm w-100" id="sidebarLogoutBtn">
                <i class="bi bi-box-arrow-right me-2"></i>退出登录
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <h4 class="mb-0">统计分析</h4>
                <div class="navbar-nav ms-auto">
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-2"></i>
                            <span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" id="navLogoutBtn"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 筛选区域 -->
        <div class="filter-card">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">统计周期</label>
                    <select class="form-select" id="periodFilter">
                        <option value="all">全部时间</option>
                        <option value="today">今天</option>
                        <option value="week">最近7天</option>
                        <option value="month">最近30天</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">开始日期</label>
                    <input type="date" class="form-control" id="startDate">
                </div>
                <div class="col-md-3">
                    <label class="form-label">结束日期</label>
                    <input type="date" class="form-control" id="endDate">
                </div>
                <div class="col-md-3">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-flex gap-2">
                        <button class="btn btn-primary" id="updateBtn">
                            <i class="bi bi-arrow-clockwise me-1"></i>更新数据
                        </button>
                        <button class="btn btn-success" id="exportBtn">
                            <i class="bi bi-download me-1"></i>导出报告
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                            <i class="bi bi-file-text"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="totalClues">0</h3>
                            <p class="text-muted mb-0">总线索数</p>
                            <small class="trend-change" id="totalTrend">-</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);">
                            <i class="bi bi-clock"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="pendingClues">0</h3>
                            <p class="text-muted mb-0">待处理</p>
                            <small class="trend-change" id="pendingTrend">-</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);">
                            <i class="bi bi-arrow-repeat"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="processingClues">0</h3>
                            <p class="text-muted mb-0">处理中</p>
                            <small class="trend-change" id="processingTrend">-</small>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="d-flex align-items-center">
                        <div class="stat-icon" style="background: linear-gradient(135deg, #d299c2 0%, #fef9d7 100%);">
                            <i class="bi bi-check-circle"></i>
                        </div>
                        <div class="ms-3">
                            <h3 class="mb-0" id="completedClues">0</h3>
                            <p class="text-muted mb-0">已完成</p>
                            <small class="trend-change" id="completedTrend">-</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <h5 class="mb-3">处理状态分布</h5>
                    <div style="height: 200px; position: relative;">
                        <canvas id="statusChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h5 class="mb-3">案件类型分布</h5>
                    <div style="height: 200px; position: relative;">
                        <canvas id="categoryChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-8">
                <div class="chart-container">
                    <h5 class="mb-3">提交趋势分析</h5>
                    <div style="height: 300px; position: relative;">
                        <canvas id="trendChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="data-table">
                    <h5 class="mb-3">地区分布统计</h5>
                    <div id="regionStats">
                        <div class="text-center py-3">
                            <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                            <p class="mt-2 text-muted">加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="chart-container">
                    <h5 class="mb-3">乡镇街道统计</h5>
                    <div style="height: 300px; position: relative;">
                        <canvas id="townshipChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 详细数据表格 -->
        <div class="data-table">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">详细统计数据</h5>
                <div class="btn-group" role="group">
                    <input type="radio" class="btn-check" name="tableView" id="categoryView" autocomplete="off" checked>
                    <label class="btn btn-outline-primary" for="categoryView">按类型</label>
                    
                    <input type="radio" class="btn-check" name="tableView" id="statusView" autocomplete="off">
                    <label class="btn btn-outline-primary" for="statusView">按状态</label>
                    
                    <input type="radio" class="btn-check" name="tableView" id="regionView" autocomplete="off">
                    <label class="btn btn-outline-primary" for="regionView">按地区</label>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr id="tableHeader">
                            <!-- 动态生成表头 -->
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 动态生成表格内容 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/admin-mobile.js"></script>
    <script>
        // 全局变量
        let statusChart, categoryChart, trendChart, townshipChart;
        let currentData = {};

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            initCharts();
            loadStatistics();
            
            // 绑定表格视图切换事件
            document.querySelectorAll('input[name="tableView"]').forEach(radio => {
                radio.addEventListener('change', updateTable);
            });
            
            // 绑定按钮事件
            bindEventListeners();
        });

        // 绑定事件监听器
        function bindEventListeners() {
            // 退出登录按钮
            const logoutButtons = [
                document.getElementById('mobileLogoutBtn'),
                document.getElementById('sidebarLogoutBtn'),
                document.getElementById('navLogoutBtn')
            ];
            
            logoutButtons.forEach(btn => {
                if (btn) {
                    btn.addEventListener('click', function(e) {
                        e.preventDefault();
                        logout();
                    });
                }
            });
            
            // 移动端菜单按钮
            const mobileMenuBtn = document.getElementById('mobileMenuBtn');
            if (mobileMenuBtn) {
                mobileMenuBtn.addEventListener('click', toggleSidebar);
            }
            
            // 更新数据按钮
            const updateBtn = document.getElementById('updateBtn');
            if (updateBtn) {
                updateBtn.addEventListener('click', updateStatistics);
            }
            
            // 导出报告按钮
            const exportBtn = document.getElementById('exportBtn');
            if (exportBtn) {
                exportBtn.addEventListener('click', exportReport);
            }
            
            // 立即登录按钮事件将在 showLoginPrompt 中动态添加
        }

        // 检查认证状态
        function checkAuth() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                // 如果从其他页面跳转过来，尝试在URL中查找token
                const urlParams = new URLSearchParams(window.location.search);
                const urlToken = urlParams.get('token');
                if (urlToken) {
                    localStorage.setItem('adminToken', urlToken);
                    // 清除URL中的token参数
                    window.history.replaceState({}, document.title, window.location.pathname);
                } else {
                    showLoginPrompt();
                    return false;
                }
            }
            
            const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
            document.getElementById('adminName').textContent = adminUser.real_name || '管理员';
            return true;
        }

        // 显示登录提示
        function showLoginPrompt() {
            const alertHtml = `
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <strong>未登录</strong> 您需要先登录才能查看统计数据。
                    <button type="button" class="btn btn-sm btn-warning ms-2" id="loginPromptBtn">
                        立即登录
                    </button>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            document.querySelector('.main-content').insertAdjacentHTML('afterbegin', alertHtml);
            
            // 绑定立即登录按钮事件
            const loginPromptBtn = document.getElementById('loginPromptBtn');
            if (loginPromptBtn) {
                loginPromptBtn.addEventListener('click', redirectToLogin);
            }
        }

        // 跳转到登录页面
        function redirectToLogin() {
            window.location.href = '/admin/login.html';
        }

        // 处理认证错误
        async function handleAuthError(response) {
            if (response.status === 401) {
                // 尝试刷新token
                const refreshed = await tryRefreshToken();
                if (!refreshed) {
                    // 刷新失败，清除token并提示重新登录
                    localStorage.removeItem('adminToken');
                    localStorage.removeItem('adminUser');
                    showLoginPrompt();
                    return false;
                }
                return true; // 刷新成功，可以重试
            }
            return false;
        }

        // 尝试刷新token
        async function tryRefreshToken() {
            const token = localStorage.getItem('adminToken');
            if (!token) return false;

            try {
                const response = await fetch('/api/admin/refresh-token', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    localStorage.setItem('adminToken', result.data.token);
                    console.log('Token刷新成功');
                    return true;
                } else {
                    console.log('Token刷新失败');
                    return false;
                }
            } catch (error) {
                console.error('Token刷新错误:', error);
                return false;
            }
        }

        // 初始化图表
        function initCharts() {
            // 状态分布饼图
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            statusChart = new Chart(statusCtx, {
                type: 'doughnut',
                data: {
                    labels: ['待处理', '处理中', '已完成', '已关闭'],
                    datasets: [{
                        data: [0, 0, 0, 0],
                        backgroundColor: ['#ffc107', '#17a2b8', '#28a745', '#dc3545'],
                        borderWidth: 0,
                        cutout: '60%'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    layout: {
                        padding: {
                            top: 10,
                            bottom: 10
                        }
                    }
                }
            });

            // 类型分布饼图
            const categoryCtx = document.getElementById('categoryChart').getContext('2d');
            categoryChart = new Chart(categoryCtx, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: ['#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe', '#00f2fe'],
                        borderWidth: 0,
                        cutout: '60%'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    layout: {
                        padding: {
                            top: 10,
                            bottom: 10
                        }
                    }
                }
            });

            // 趋势折线图
            const trendCtx = document.getElementById('trendChart').getContext('2d');
            trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '线索提交数量',
                        data: [],
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });

            // 乡镇统计柱状图
            const townshipCtx = document.getElementById('townshipChart').getContext('2d');
            townshipChart = new Chart(townshipCtx, {
                type: 'bar',
                data: {
                    labels: [],
                    datasets: [{
                        label: '线索数量',
                        data: [],
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        }
                    }
                }
            });
        }

        // 加载统计数据
        async function loadStatistics() {
            if (!checkAuth()) {
                return;
            }

            try {
                const token = localStorage.getItem('adminToken');
                const period = document.getElementById('periodFilter').value;
                
                // 构建查询参数
                const params = new URLSearchParams({ period });
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                
                if (startDate) params.append('start_date', startDate);
                if (endDate) params.append('end_date', endDate);
                
                const response = await fetch(`/api/admin/statistics/overview?${params}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    currentData = result.data;
                    
                    updateStatCards(currentData);
                    updateCharts(currentData);
                    updateRegionStats(currentData.region_stats || []);
                    updateTable();
                    
                    // 加载趋势数据
                    loadTrendData();
                } else {
                    // 处理认证错误
                    const authHandled = await handleAuthError(response);
                    if (authHandled) {
                        // 重试加载
                        setTimeout(loadStatistics, 1000);
                    } else {
                        throw new Error(`加载统计数据失败: ${response.status} ${response.statusText}`);
                    }
                }
            } catch (error) {
                console.error('加载统计数据失败:', error);
                showErrorAlert('加载统计数据失败，请刷新页面重试或联系管理员');
            }
        }

        // 加载趋势数据
        async function loadTrendData() {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch('/api/admin/statistics/trends?type=submission&period=30d', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;
                    
                    trendChart.data.labels = data.dates.map(date => formatDate(date));
                    trendChart.data.datasets[0].data = data.values;
                    trendChart.update();
                } else {
                    // 处理认证错误
                    const authHandled = await handleAuthError(response);
                    if (authHandled) {
                        // 重试加载
                        setTimeout(loadTrendData, 1000);
                    }
                }
            } catch (error) {
                console.error('加载趋势数据失败:', error);
            }
        }

        // 更新统计卡片
        function updateStatCards(data) {
            document.getElementById('totalClues').textContent = data.total_clues || 0;
            document.getElementById('pendingClues').textContent = data.pending_clues || 0;
            document.getElementById('processingClues').textContent = data.processing_clues || 0;
            document.getElementById('completedClues').textContent = data.completed_clues || 0;
            
            // 计算趋势（简化版）
            const todayClues = data.today_clues || 0;
            updateTrendIndicator('totalTrend', todayClues > 0 ? 'up' : 'stable', `今日新增 ${todayClues}`);
            updateTrendIndicator('pendingTrend', data.pending_clues > 0 ? 'up' : 'stable', `待处理 ${data.pending_clues || 0}`);
            updateTrendIndicator('processingTrend', data.processing_clues > 0 ? 'up' : 'stable', `处理中 ${data.processing_clues || 0}`);
            updateTrendIndicator('completedTrend', data.completed_clues > 0 ? 'up' : 'stable', `已完成 ${data.completed_clues || 0}`);
        }

        // 更新趋势指示器
        function updateTrendIndicator(elementId, trend, text) {
            const element = document.getElementById(elementId);
            element.className = `trend-change trend-${trend}`;
            element.textContent = text;
        }

        // 更新图表
        function updateCharts(data) {
            // 更新状态图表
            statusChart.data.datasets[0].data = [
                data.pending_clues || 0,
                data.processing_clues || 0,
                data.completed_clues || 0,
                data.closed_clues || 0
            ];
            statusChart.update();

            // 更新类型图表
            const categoryStats = data.category_stats || [];
            categoryChart.data.labels = categoryStats.map(item => item.category);
            categoryChart.data.datasets[0].data = categoryStats.map(item => item.count);
            categoryChart.update();

            // 更新乡镇图表
            const townshipStats = data.township_stats || [];
            townshipChart.data.labels = townshipStats.map(item => item.township_name || item.region || '未知');
            townshipChart.data.datasets[0].data = townshipStats.map(item => item.count);
            townshipChart.update();
        }

        // 更新地区统计
        function updateRegionStats(regionStats) {
            const container = document.getElementById('regionStats');
            
            if (regionStats.length === 0) {
                container.innerHTML = '<p class="text-muted text-center">暂无地区数据</p>';
                return;
            }
            
            container.innerHTML = regionStats.map(item => `
                <div class="trend-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <span>${item.region || '未知地区'}</span>
                        <span class="trend-value">${item.count}</span>
                    </div>
                    <div class="progress mt-1" style="height: 4px;">
                        <div class="progress-bar" role="progressbar" 
                             style="width: ${(item.count / Math.max(...regionStats.map(r => r.count))) * 100}%"></div>
                    </div>
                </div>
            `).join('');
        }

        // 更新表格
        function updateTable() {
            const selectedView = document.querySelector('input[name="tableView"]:checked').id;
            const tableHeader = document.getElementById('tableHeader');
            const tableBody = document.getElementById('tableBody');
            
            let data = [];
            let headers = [];
            
            switch (selectedView) {
                case 'categoryView':
                    headers = ['类型', '数量', '占比', '待处理', '处理中', '已完成'];
                    data = currentData.category_stats || [];
                    break;
                case 'statusView':
                    headers = ['状态', '数量', '占比'];
                    data = [
                        { name: '待处理', count: currentData.pending_clues || 0 },
                        { name: '处理中', count: currentData.processing_clues || 0 },
                        { name: '已完成', count: currentData.completed_clues || 0 },
                        { name: '已关闭', count: currentData.closed_clues || 0 }
                    ];
                    break;
                case 'regionView':
                    headers = ['地区', '数量', '占比'];
                    data = currentData.region_stats || [];
                    break;
            }
            
            // 生成表头
            tableHeader.innerHTML = headers.map(header => `<th>${header}</th>`).join('');
            
            // 生成表格内容
            const total = data.reduce((sum, item) => sum + (item.count || 0), 0);
            
            tableBody.innerHTML = data.map(item => {
                const count = item.count || 0;
                const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : '0.0';
                
                if (selectedView === 'categoryView') {
                    return `
                        <tr>
                            <td>${item.category || item.name}</td>
                            <td>${count}</td>
                            <td>${percentage}%</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                        </tr>
                    `;
                } else {
                    return `
                        <tr>
                            <td>${item.region || item.name || item.category}</td>
                            <td>${count}</td>
                            <td>${percentage}%</td>
                        </tr>
                    `;
                }
            }).join('');
        }

        // 更新统计数据
        function updateStatistics() {
            loadStatistics();
        }

        // 导出报告
        function exportReport() {
            const token = localStorage.getItem('adminToken');
            const period = document.getElementById('periodFilter').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            const params = new URLSearchParams({ format: 'excel', period });
            if (startDate) params.append('start_date', startDate);
            if (endDate) params.append('end_date', endDate);
            
            const url = `/api/admin/statistics/export?${params}&token=${token}`;
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = url;
            link.download = `统计报告_${new Date().toISOString().split('T')[0]}.xlsx`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 工具函数
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }

        // 退出登录
        async function logout() {
            try {
                const token = localStorage.getItem('adminToken');
                
                // 如果有token，先调用后端退出接口
                if (token) {
                    try {
                        const response = await fetch('/api/admin/logout', {
                            method: 'POST',
                            headers: {
                                'Authorization': `Bearer ${token}`,
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const result = await response.json();
                        console.log('退出登录响应:', result);
                    } catch (error) {
                        console.error('调用退出接口失败:', error);
                        // 即使接口调用失败，也继续清除本地数据
                    }
                }
                
                // 清除本地存储
                localStorage.removeItem('adminToken');
                localStorage.removeItem('adminUser');
                
                // 显示退出成功提示
                const alertHtml = `
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>退出成功</strong> 您已成功退出登录。
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                `;
                document.querySelector('.main-content').insertAdjacentHTML('afterbegin', alertHtml);
                
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = '/admin/login.html';
                }, 1500);
                
            } catch (error) {
                console.error('退出登录失败:', error);
                
                // 即使出错也清除本地数据并跳转
                localStorage.removeItem('adminToken');
                localStorage.removeItem('adminUser');
                
                showErrorAlert('退出登录时发生错误，但已清除本地认证信息');
                
                setTimeout(() => {
                    window.location.href = '/admin/login.html';
                }, 2000);
            }
        }

        // 显示错误提示
        function showErrorAlert(message) {
            const alertHtml = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <strong>错误</strong> ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            document.querySelector('.main-content').insertAdjacentHTML('afterbegin', alertHtml);
        }

        // 添加 toggleSidebar 函数
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            const overlay = document.querySelector('.sidebar-overlay');
            
            if (sidebar && overlay) {
                sidebar.classList.toggle('show');
                overlay.classList.toggle('show');
            }
        }
    </script>
</body>
</html> 